package ynny.xxxy.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//      4、添加客户端凭证
        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("123456"))
                .authorizedGrantTypes("authorization_code","implicit","password","client_credentials")//授权模式,授权码模式、简化模式、密码模式、客户端模式
                .scopes("test")
                .redirectUris("http://www.baidu.com");
//                .autoApprove(false);//默认是true，自动授权
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//      5、打开auth2.0的授权模式
        security.tokenKeyAccess("permitAll()")//获取token
                .checkTokenAccess("isAuthenticated()")//检查token
                .allowFormAuthenticationForClients();//允许表单认证
    }

    //    使用密码的方式必须重写授权服务器的configure方法，并调用授权管理器
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

}
